

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class MyAppBar extends StatelessWidget implements PreferredSizeWidget{
  final String title;
  Widget? leading;
  Widget? centraling;
  Widget? trailing;
  bool needBack;
  bool needUnderLine;
  final Color? backgroundColor;
  VoidCallback? backBlock;
  MyAppBar({
    Key? key,
    this.title = '',
    this.leading,
    this.centraling,
    this.trailing,
    this.backgroundColor,
    this.needBack = true,
    this.backBlock,
    this.needUnderLine = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final Color bgColor = backgroundColor ?? Theme.of(context).scaffoldBackgroundColor;

    final SystemUiOverlayStyle overlayStyle = ThemeData.estimateBrightnessForColor(bgColor) == Brightness.dark
        ? SystemUiOverlayStyle.light : SystemUiOverlayStyle.dark;
    final Widget backWidget = IconButton(
        onPressed: () async{
          FocusManager.instance.primaryFocus?.unfocus();
          final isBack = await Navigator.maybePop(context);
          if (!isBack) {
            await SystemNavigator.pop();
          }
          if(backBlock != null) backBlock!();
        },
        icon: Image.asset("images/back_black.png"),

        padding: const EdgeInsets.all(12.0),
    );

    final Widget titleWidget = Container(
      alignment: Alignment.center,

      child: Text(
        title,
        style: const TextStyle(
          color: Color(0xFF222222),
          fontSize: 18,
          fontWeight: FontWeight.bold,
        ),
      ),
    );

    List<Widget> barItems = [];
    leading ??= needBack ? backWidget : null;
    centraling ??= titleWidget;

    Widget? trailingWidget = trailing != null ? Positioned(
      right: 15,
        child: trailing!
    ) : null;

    Widget underLineWidget = Positioned(
      bottom: 0,
      width: MediaQuery.of(context).size.width,
      height: 1,
      child: Container(
        color: Color(0xFFF1F1F1),
      ),
    );
    leading != null ? barItems.add(leading!) : null;
    centraling != null ? barItems.add(centraling!) : null;
    trailingWidget != null ? barItems.add(trailingWidget!) : null;
    needUnderLine ? barItems.add(underLineWidget) : null;
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: overlayStyle,
      child:Material(
        color: bgColor,
        child: SafeArea(
          child: Stack(
            alignment: Alignment.centerLeft,
            children: barItems,
          ),
        ),
      )
    );
  }


  @override
  Size get preferredSize => const Size.fromHeight(44.0);
}
